using System;
using System.Collections.ObjectModel;
using System.Linq;
using EstimateTracker.Domain.Entities;
using EstimateTracker.Events;
using EstimateTracker.Services;
using JetBrains.Annotations;
using Microsoft.Practices.Prism.Events;

namespace EstimateTracker.ViewModels
{
    public class ProjectViewModel : ViewModelBase
    {
        private readonly ObservableCollection<Project> _projects;
        private readonly IEventAggregator _eventAggregator;
        private readonly IProjectService _projectService;
        private Project _selectedProject;

        public ProjectViewModel([NotNull] IEventAggregator eventAggregator, [NotNull] IProjectService projectService)
        {
            if (eventAggregator == null) throw new ArgumentNullException("eventAggregator");
            if (projectService == null) throw new ArgumentNullException("projectService");

            _eventAggregator = eventAggregator;
            _projectService = projectService;
            _projects = new ObservableCollection<Project>();
        }

        public ObservableCollection<Project> Projects
        {
            get
            {
                _projectService.FindAllProjects(_projects);
                SelectedProject = _projects.Any() ? _projects.First() : SelectedProject;
                return _projects;
            }
        }

        public Project SelectedProject
        {
            get { return _selectedProject; }
            set
            {
                _selectedProject = value;
                if (_selectedProject != null)
                {
                    DisplayActivitiesEvent displayActivitiesEvent = _eventAggregator.GetEvent<DisplayActivitiesEvent>();
                    displayActivitiesEvent.Publish(_selectedProject.Id);
                }
                OnPropertyChanged("SelectedProject");
            }
        }

        public void AddProject(string projectName)
        {
            _projectService.SaveProject(projectName, Projects);
        }
    }
}